<template>
  <div class="edit-container">
    <el-tree ref="tree" :data="menuTree" node-key="id" :props="defaultProps" default-expand-all check-strictly draggable @node-drop="handleDrop" @node-contextmenu="handleContextmenu" :allow-drag="allowDrop" />
  </div>
</template>

<script>
export default {
  inject: ['reload'],
  data () {
    return {
      size: 'mini',
      menuTree: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      }
    }
  },
  methods: {
    loadData () {
      this.$api.menu.getTree().then(res => {
        if (res.code === 0) {
          this.menuTree = res.data
        }
      })
    },
    handleContextmenu (ev, node) {
      this.$prompt('', '修改菜单名称', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: node.label
      }).then(({ value }) => {
        this.$api.menu.save({ id: node.id, label: value }).then((res) => {
          if (res.code === 0) {
            this.$message({ message: '修改成功', type: 'success' })
            this.reload()
          } else {
            this.$message({ message: '修改失败, ' + res.message, type: 'error' })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消修改'
        })
      })
    },
    handleDrop (draggingNode, dropNode, dropType, ev) {
      let params = { id: draggingNode.data.id }
      if (dropType === 'before') {
        params['parentId'] = dropNode.data.parentId
        params['sort'] = dropNode.data.sort
      } else if (dropType === 'after') {
        params['parentId'] = dropNode.data.parentId
        params['sort'] = dropNode.data.sort + 1
      } else if (dropType === 'inner') {
        params['parentId'] = dropNode.data.id
        params['sort'] = 0
      }
      this.$api.menu.move(params).then((res) => {
        if (res.code === 0) {
          this.$message({ message: '移动成功', type: 'success' })
        } else {
          this.$message({ message: '移动失败, ' + res.message, type: 'error' })
        }
      })
    },
    allowDrop (draggingNode, dropNode, type) {
      return this.$_has('system:menu:edit')
    }
  },
  mounted () {
    this.loadData()
  }
}
</script>
